package sdk.pay;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.*;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ServiceInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.*;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.mtdl.dlpaysdk.activity.DLPayManager;
import com.mtdl.dlpaysdk.callback.DLCallBack;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import org.json.JSONException;
import org.json.JSONObject;
import sdk.pay.easypermissions.EasyPermissions;
import sdk.pay.helper.OpenAccessibilitySettingHelper;
import sdk.pay.helper.PayAssistant;
import sdk.pay.listener.PayGetPayStatusListener;
import sdk.pay.model.PayInfo;
import sdk.pay.service.PayAccessibilityService;
import sdk.pay.utils.PayLogUtil;
import sdk.pay.utils.PayToastUtil;

import java.io.InputStream;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static android.app.AlertDialog.THEME_HOLO_LIGHT;
import static android.graphics.Color.BLACK;
import static android.graphics.Color.WHITE;
import static sdk.pay.constant.PayConstant.*;
import static sdk.pay.constant.PayExternalConstant.*;

/**
 * Created by lj on 2017/8/23 0023.
 */

public class PayExcessiveActivity extends Activity implements EasyPermissions.PermissionCallbacks {
    private Button mFinishPay;
    private Button mUnFinishPay;
    protected Dialog mProgressDialog;
    private static PayHelperIml sPayHelperIml;
    private static PayInfo sPayInfo;
    private static boolean sPayStatusCallBack;
    private static PayWebView sPayWebView;
    private static Activity sActivity;
    private static final String PAY_WEB_VIEW = "0";
    private static final String PAY_WEB_VIEW_ACTIVITY = "1";
    private static final String PAY_BROWSER = "2";
    private static final String PAY_SPECIAL = "3";
    //支付宝从客户端拉起
    private static final String PAY_MODE4 = "4";
    private static final String PAY_MODE5 = "5";
    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
    private static final String IMAGE_FILE_NAME = "image_icon_pay_excessive.png";
    //Is  transparent?
    private boolean mTransparent = false;
    private AccessibilityServiceReceiver mAccessibilityServiceReceiver;
    private static final String ZHANG_LING_SMALL_PAY_TYPE = "zhanglingmppay";
    private static final int REQUEST_READ_PHONE_STATE = 0x1;
    private static final int REQUEST_APP_SETTING = 0x1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAccessibilityServiceReceiver = new AccessibilityServiceReceiver();
        registerAccessibilityServiceReceiver();
        initView();
    }

    /**
     * 如果是小程序的话,获得权限返回true,没有权限返回false
     * 不是小程序的话,返回true
     *
     * @return
     */
    private boolean isSmallWxPayEnabled() {
        try {
            String url = sPayInfo.getUrl();
            JSONObject jsonObject = new JSONObject(url);
            String type = jsonObject.getString("ProcessingType");
            if (ZHANG_LING_SMALL_PAY_TYPE.equalsIgnoreCase(type)) {
                if (EasyPermissions.hasPermissions(this, Manifest.permission.READ_PHONE_STATE)) {
                    return true;
                } else {
                    return false;
                }
            }
        } catch (JSONException e) {
            PayLogUtil.logBase("isSmallWxPayEnabled exception " + e.getMessage());
            e.printStackTrace();
        }
        return true;
    }

    @Override
    protected void onStart() {
        super.onStart();
        smallWxPayRequestPermission();
    }

    /**
     * 小程序请求获取手机信息权限
     */
    private void smallWxPayRequestPermission() {
        try {
            String url = sPayInfo.getUrl();
            JSONObject jsonObject = new JSONObject(url);
            String type = jsonObject.getString("ProcessingType");
            PayLogUtil.logBase("type = " + type);
            if (ZHANG_LING_SMALL_PAY_TYPE.equalsIgnoreCase(type)) {
                if (!EasyPermissions.hasPermissions(this, Manifest.permission.READ_PHONE_STATE)) {
                    EasyPermissions.requestPermissions(this, "获取手机信息权限", REQUEST_READ_PHONE_STATE, Manifest.permission.READ_PHONE_STATE);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            PayLogUtil.logBase("smallWxPayRequestPermission exception " + e.getMessage());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null == sPayInfo) {
            finish();
            return;
        }
        boolean canPay = canContinuePay();
        boolean checkPermission = isSmallWxPayEnabled();
        PayLogUtil.logBase("onResume canPay = " + canPay + " mTransparent = " + mTransparent);
        if (canPay && checkPermission) {
            commitBtnClickable(true);
            if (!sPayInfo.getIsPaying()) {
                selectPay();
            } else if (mTransparent) {
                queryStatus(true);
            } else {
                dismiss();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        commitBtnClickable(false);
        dismiss();
        if (!mTransparent) {
            showProgressDialog(LOADING, false);
        }
    }

    @Override
    protected void onDestroy() {
        if (null != sPayInfo) {
            sPayInfo.setIsPaying(false);
        }
        dismiss();
        unRegisterAccessibilityServiceReceiver();
        super.onDestroy();
    }

    private void initView() {
        closePayPage();
        setTranslucent(true);
        showProgressDialog(LOADING, false);
        interfaceLayout();
    }

    /**
     * @param flag false 不透明  true 透明
     */
    private void setTranslucent(boolean flag) {
        mTransparent = flag;
        Window window = getWindow();
        // 获取对话框当前的参数值
        WindowManager.LayoutParams windowLayoutParams = window.getAttributes();
        // 设置透明度
        if (flag) {
            windowLayoutParams.alpha = 0.0f;
        } else {
            windowLayoutParams.alpha = 1.0f;
        }
        getWindow().setAttributes(windowLayoutParams);
    }

    private void interfaceLayout() {
        Display display = getWindowManager().getDefaultDisplay();
        final int blue = Color.rgb(72, 148, 232);
        final int gray = Color.rgb(153, 153, 153);
        mUnFinishPay = new Button(this);
        mFinishPay = new Button(this);
        RelativeLayout mRelativeLayout = new RelativeLayout(getApplicationContext());
        mRelativeLayout.setId(generateViewId());
        mUnFinishPay.setId(generateViewId());
        mFinishPay.setId(generateViewId());
        mRelativeLayout.setBackgroundColor(WHITE);
        mFinishPay.setText(UN_FINISH_PAY);
        mFinishPay.setTextColor(WHITE);
        mFinishPay.setBackgroundDrawable(drawRectangular(0, blue));
        mUnFinishPay.setText(FINISH_PAY);
        mUnFinishPay.setTextColor(blue);
        mUnFinishPay.setBackgroundDrawable(drawRectangular(1, WHITE));
        ImageView imageView = new ImageView(this);
        imageView.setId(generateViewId());
        imageView.setBackgroundDrawable(loadImageFromAsserts(this));
        RelativeLayout.LayoutParams layteImageView = new RelativeLayout.LayoutParams(
                dip2px(100),
                dip2px(100)
        );
        if (isPortrait()) {
            layteImageView.setMargins(0, dip2px(115), 0, 0);
        } else {
            layteImageView.setMargins(0, dip2px(40), 0, 0);
        }
        layteImageView.addRule(RelativeLayout.CENTER_HORIZONTAL);
        mRelativeLayout.addView(imageView, layteImageView);

        TextView tvFinishPay = new TextView(this);
        tvFinishPay.setId(generateViewId());
        tvFinishPay.setText(TV_FINISH_PAY);
        tvFinishPay.setTextSize(dip2px(5));
        tvFinishPay.setTextColor(gray);
        RelativeLayout.LayoutParams tvFinish = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT
        );
        tvFinish.addRule(RelativeLayout.CENTER_HORIZONTAL);
        tvFinish.setMargins(0, dip2px(30), 0, 0);
        tvFinish.addRule(RelativeLayout.BELOW, imageView.getId());
        mRelativeLayout.addView(tvFinishPay, tvFinish);

        TextView tvUnFinishPay = new TextView(this);
        tvUnFinishPay.setId(generateViewId());
        tvUnFinishPay.setText(TV_UN_FINISH_PAY);
        tvUnFinishPay.setTextSize(dip2px(5));
        tvUnFinishPay.setTextColor(gray);
        RelativeLayout.LayoutParams tvUnFinish = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT
        );
        tvUnFinish.addRule(RelativeLayout.BELOW, tvFinishPay.getId());
        tvUnFinish.addRule(RelativeLayout.CENTER_HORIZONTAL);
        tvUnFinish.setMargins(0, dip2px(10), 0, 0);
        mRelativeLayout.addView(tvUnFinishPay, tvUnFinish);

        if (isPortrait()) {
            RelativeLayout.LayoutParams layoutFinishPay = new RelativeLayout.LayoutParams(
                    display.getWidth() * 3 / 4,
                    dip2px(40)
            );
            layoutFinishPay.addRule(RelativeLayout.BELOW, tvUnFinishPay.getId());
            layoutFinishPay.setMargins(0, dip2px(40), 0, 0);
            layoutFinishPay.addRule(RelativeLayout.CENTER_HORIZONTAL);
            mRelativeLayout.addView(mFinishPay, layoutFinishPay);
            RelativeLayout.LayoutParams layoutUnFinishPay = new RelativeLayout.LayoutParams(
                    display.getWidth() * 3 / 4,
                    dip2px(40)
            );
            layoutUnFinishPay.setMargins(0, dip2px(20), 0, 0);
            layoutUnFinishPay.addRule(RelativeLayout.BELOW, mFinishPay.getId());
            layoutUnFinishPay.addRule(RelativeLayout.CENTER_HORIZONTAL);
            mRelativeLayout.addView(mUnFinishPay, layoutUnFinishPay);
        } else {
            RelativeLayout.LayoutParams layoutFinishPay = new RelativeLayout.LayoutParams(
                    display.getWidth() / 3,
                    dip2px(40)
            );
            layoutFinishPay.addRule(RelativeLayout.BELOW, tvUnFinishPay.getId());
            layoutFinishPay.setMargins(display.getWidth() / 6 - dip2px(20), dip2px(30), 0, 0);
            mRelativeLayout.addView(mFinishPay, layoutFinishPay);

            RelativeLayout.LayoutParams layoutUnFinishPay = new RelativeLayout.LayoutParams(
                    display.getWidth() / 3,
                    dip2px(40)
            );
            layoutUnFinishPay.setMargins(dip2px(40), dip2px(30), 0, 0);
            layoutUnFinishPay.addRule(RelativeLayout.BELOW, tvUnFinishPay.getId());
            layoutUnFinishPay.addRule(RelativeLayout.RIGHT_OF, mFinishPay.getId());
            mRelativeLayout.addView(mUnFinishPay, layoutUnFinishPay);
        }
        setContentView(mRelativeLayout);
        mUnFinishPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                queryStatus(false);
            }
        });
        mFinishPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                queryStatus(false);
            }
        });
    }

    private Drawable drawRectangular(int i, int color) {
        GradientDrawable mDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{color, color});
        mDrawable.setShape(GradientDrawable.RECTANGLE);
        mDrawable.setGradientType(GradientDrawable.LINEAR_GRADIENT);
        mDrawable.setCornerRadii(new float[]{10, 10, 10, 10, 10, 10, 10, 10});
        if (i == 1) {
            mDrawable.setStroke(1, Color.rgb(72, 148, 232));
            return mDrawable;
        }
        return mDrawable;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        interfaceLayout();
    }

    private boolean isPortrait() {
        return getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    /**
     * query pay result Status
     *
     * @param flag true 自动查询 false 手动查询
     */
    private void queryStatus(final boolean flag) {
        PayLogUtil.logBase("queryStatus flag = " + flag + " sPayStatusCallBack = " + sPayStatusCallBack);
        if (!sPayStatusCallBack) {
            finish();
            return;
        }
        showProgressDialog(LOADING, true);
        sPayHelperIml.getPayStatus(new PayGetPayStatusListener() {
            @Override
            public void onPayStatus(int payStatus) {
                PayLogUtil.logBase("queryStatus flag = " + flag + " payStatus = " + payStatus);
                dismiss();
                if (flag) {
                    if (payStatus == FAILURE) {
                        setTranslucent(false);
                    } else if (payStatus == ERROR) {
                        finish();
                    } else {
                        goBack(payStatus);
                    }
                } else {
                    goBack(payStatus);
                }
            }
        });
    }

    /**
     * go back with pay result
     *
     * @param payStatus pay result
     */
    private void goBack(int payStatus) {
        PayLogUtil.logBase("goBack payStatus " + payStatus);
        Intent intent = new Intent(ACTION_PAY_CALLBACK);
        intent.putExtra(PAY_STATUS, payStatus);
        LocalBroadcastManager.getInstance(sActivity).sendBroadcast(intent);
        PayExcessiveActivity.this.setResult(RESULT_CODE, intent);
        finish();
    }

    /**
     * select the type for pay
     */
    private void selectPay() {
        String url = sPayInfo.getUrl();
        String action = sPayInfo.getAction();
        String typeId = sPayInfo.getPayTypeId();
        PayLogUtil.logBase("selectPay url = " + url + " action = " + action);
        if (TextUtils.isEmpty(url)) {
            PayLogUtil.logSecond("Pay url is empty");
            return;
        }
        if (TextUtils.isEmpty(action)) {
            PayLogUtil.logSecond("Pay action is empty");
            return;
        }
        if (TextUtils.isEmpty(typeId)) {
            PayLogUtil.logSecond("Pay typeId is empty");
            return;
        }
        if (TextUtils.isEmpty(url) || !url.toLowerCase().startsWith("http")) {
            PayLogUtil.logFirst("url = " + url + " action = " + action + " typeId = " + typeId);
        }
        sPayInfo.setIsPaying(true);
        sPayInfo.setPayTypeId("");
        switch (action) {
            case PAY_WEB_VIEW:
                sPayWebView.loadUrl(url);
                break;
            case PAY_WEB_VIEW_ACTIVITY:
                PayWebViewActivity.startActivity(sActivity, url);
                break;
            case PAY_BROWSER:
                jumpBrowser();
                break;
            case PAY_SPECIAL:
                try {
                    JSONObject jsonObject = new JSONObject(url);
                    String data = jsonObject.getString("ProcessingData");
                    String type = jsonObject.getString("ProcessingType");
                    PayLogUtil.logBase("type = " + type);
                    JSONObject jsonData = new JSONObject(data);
                    if (ZHANG_LING_SMALL_PAY_TYPE.equalsIgnoreCase(type)) {
                        int amount = jsonData.getInt("amount");
                        String appid = jsonData.getString("appid");
                        String appkey = jsonData.getString("appkey");
                        String body = jsonData.getString("body");
                        String notifyUrl = jsonData.getString("notifyUrl");
                        String subject = jsonData.getString("subject");
                        String mchntOrderNo = jsonData.getString("mchntOrderNo");
                        smallWxPay(amount, appid, appkey, body, notifyUrl, subject, mchntOrderNo);
                    } else {
                        String appid = jsonData.getString("appid");
                        String noncestr = jsonData.getString("noncestr");
                        String packageValue = jsonData.getString("package");
                        String partnerid = jsonData.getString("partnerid");
                        String paySign = jsonData.getString("paySign");
                        String prepayid = jsonData.getString("prepayid");
                        String timestamp = jsonData.getString("timestamp");
                        PayLogUtil.logBase(String.format("appid = %s,noncestr = %s,packageValue = %s,partnerid = %s,paySign = %s,prepayid = %s,timestamp = %s",
                                appid, noncestr, packageValue, partnerid, paySign, prepayid, timestamp));
                        IWXAPI iwxapi = WXAPIFactory.createWXAPI(this, appid);
                        iwxapi.registerApp(appid);
                        PayReq payReq = new PayReq();
                        payReq.appId = appid;
                        payReq.nonceStr = noncestr;
                        payReq.packageValue = packageValue;
                        payReq.partnerId = partnerid;
                        payReq.sign = paySign;
                        payReq.prepayId = prepayid;
                        payReq.timeStamp = timestamp;
                        iwxapi.sendReq(payReq);
                    }

                } catch (JSONException e) {
                    PayLogUtil.logBase("exception reason " + e.getMessage());
                    e.printStackTrace();
                }
                break;
            case PAY_MODE4:
                try {
                    String postData = sPayInfo.getPostData();
                    JSONObject jsonData = new JSONObject(postData);
                    String money = jsonData.getString("Money");
                    String remark = jsonData.getString("Reason");
                    PayLogUtil.logBase(String.format("money = %s, remark = %s", money, remark));
                    if (!TextUtils.isEmpty(money) && !TextUtils.isEmpty(remark)) {
                        PayLogUtil.logBase("load url = " + url);
                        PayAssistant.setsCanUseState(true);
                        PayAssistant.setMoney(money);
                        PayAssistant.setRemark(remark);
                        sPayInfo.setPayTypeId(typeId);
                        startAliQrActivity();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case PAY_MODE5:
                try {
                    String postData = sPayInfo.getPostData();
                    JSONObject jsonData = new JSONObject(postData);
                    String money = jsonData.getString("Money");
                    String remark = jsonData.getString("Reason");
                    PayLogUtil.logBase(String.format("money = %s, remark = %s", money, remark));
                    if (!TextUtils.isEmpty(money) && !TextUtils.isEmpty(remark)) {
                        PayAssistant.setsCanUseState(true);
                        PayAssistant.setMoney(money);
                        PayAssistant.setRemark(remark);
                        jumpAliZhiPay();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void smallWxPay(int amount, String appid, String appkey, String body, String notifyUrl, String subject, String mchntOrderNo) {
        PayLogUtil.logBase(String.format("smallWxPay amount = %d, appid = %s,notifyUrl = %s,mchntOrderNo = %s", amount, appid, notifyUrl, mchntOrderNo));
        DLPayManager manager = DLPayManager.getInstance(sActivity, appid);
        manager.startDLPaysdk(appkey, subject, amount, body, mchntOrderNo, notifyUrl, "", "", "", DLCallBack.PAY_WITH_WEIXIN, new DLCallBack() {
            @Override
            public void dlPayResult(String payResultCode, String msgs) {
            }
        });
        //延时关闭小程序的那个空白页的界面
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                DLPayManager.isPaySuccess(true);
            }
        }, 3000L);
    }

    private void startAliQrActivity() {
        Uri uri = Uri.parse("alipays://platformapi/startapp?appId=10000007");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    private void jumpAliZhiPay() {
        ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText("吱口令", "#吱口令#长按复制此条消息，打开支付宝给我转账3CjEii44bg");
        clipboardManager.setPrimaryClip(clipData);
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.eg.android.AlipayGphone", "com.alipay.mobile.quinox.LauncherActivity"));
        startActivity(intent);
    }

    /**
     * web browser open the pay url
     */
    private void jumpBrowser() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri content_url = Uri.parse(sPayInfo.getUrl());
        intent.setData(content_url);
        startActivity(intent);
    }

    /**
     * static method to start the activity
     *
     * @param activity          ori activity where start
     * @param payHelperIml      the class payHelperIml
     * @param payInfo           model payInfo
     * @param payWebView        pay webView
     * @param payStatusCallBack pay result callback
     */
    public static void startActivityForResult(Activity activity, PayHelperIml payHelperIml,
                                              PayInfo payInfo, PayWebView payWebView,
                                              boolean payStatusCallBack) {
        sActivity = activity;
        sPayStatusCallBack = payStatusCallBack;
        sPayHelperIml = payHelperIml;
        sPayInfo = payInfo;
        sPayWebView = payWebView;
        Intent intent = new Intent(activity, PayExcessiveActivity.class);
        activity.startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            dismiss();
            showDialog();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showDialog() {
        TextView title = new TextView(this);
        title.setText(CONFIRM_PAY);
        title.setTextColor(BLACK);
        title.setPadding(10, 25, 10, 25);
        title.setGravity(Gravity.CENTER);
        title.setTextSize(20);
        new AlertDialog.Builder(this, THEME_HOLO_LIGHT)
                .setCustomTitle(title)
                .setCancelable(false)
                .setPositiveButton(FINISH_PAY, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        queryStatus(false);
                    }
                })
                .setNegativeButton(UN_FINISH_PAY, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        queryStatus(false);
                    }
                }).show();
    }

    private void showProgressDialog(String msg, boolean cancelable) {
        if (null == mProgressDialog || !mProgressDialog.isShowing()) {
            mProgressDialog = ProgressDialog.show(this, "", msg, false, cancelable, null);
        }
    }

    private void dismiss() {
        if (null != mProgressDialog && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private int dip2px(float dpValue) {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private int generateViewId() {
        for (; ; ) {
            final int result = sNextGeneratedId.get();
            int newValue = result + 1;
            if (newValue > 0x00FFFFFF) {
                newValue = 1;
            }
            if (sNextGeneratedId.compareAndSet(result, newValue)) {
                return result;
            }
        }
    }

    private Drawable loadImageFromAsserts(final Context context) {
        try {
            InputStream is = context.getResources().getAssets().open(IMAGE_FILE_NAME);
            return Drawable.createFromStream(is, null);
        } catch (OutOfMemoryError | Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void closePayPage() {
        Intent intent = new Intent();
        intent.setAction("com.pay.close");
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    private void commitBtnClickable(boolean clickable) {
        mFinishPay.setClickable(clickable);
        mUnFinishPay.setClickable(clickable);
    }

    /**
     * 检查是否可以继续支付
     *
     * @return true(可以继续支付), false(不能继续支付去开启权限)
     */
    private boolean canContinuePay() {
        String action = sPayInfo.getAction();
        if (PAY_MODE4.equals(action)) {
            try {
                PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SERVICES);
                ServiceInfo[] serviceInfo = packageInfo.services;
                for (ServiceInfo info : serviceInfo) {
                    if (info.name.equals(PayAccessibilityService.class.getCanonicalName())) {
                        int id = info.labelRes;
                        String label = sActivity.getString(id);
                        label = label.trim();
                        if (!OpenAccessibilitySettingHelper.isAccessibilitySettingsOn(sActivity, PayAccessibilityService.class.getName())) {
                            PayToastUtil.showCustomInfo(sActivity, PAY_TIPS_PREFIX + label + PAY_TIPS_SUFFIX, TOAST_SHOW_TIME);
                            OpenAccessibilitySettingHelper.jumpToSettingPage(sActivity);
                            return false;
                        } else {
                            return true;
                        }
                    }
                }
            } catch (PackageManager.NameNotFoundException e) {
                throw new RuntimeException(PAY_EXCEPTION);
            }
        }
        return true;
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == REQUEST_READ_PHONE_STATE) {
            reSmallWxPayNext();
        }
    }

    /**
     * 授权后继续小程序支付
     */
    private void reSmallWxPayNext() {
        try {
            String url = sPayInfo.getUrl();
            JSONObject jsonObject = new JSONObject(url);
            String data = jsonObject.getString("ProcessingData");
            JSONObject jsonData = new JSONObject(data);
            int amount = jsonData.getInt("amount");
            String appid = jsonData.getString("appid");
            String appkey = jsonData.getString("appkey");
            String body = jsonData.getString("body");
            String notifyUrl = jsonData.getString("notifyUrl");
            String subject = jsonData.getString("subject");
            String mchntOrderNo = jsonData.getString("mchntOrderNo");
            smallWxPay(amount, appid, appkey, body, notifyUrl, subject, mchntOrderNo);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        showSettingDialog();
    }

    private void showSettingDialog() {
        new AlertDialog.Builder(this)
                .setTitle("权限管理设置获取手机信息权限为允许,否则不能正常支付!")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setPositiveButton("设置权限", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivityForResult(new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + getPackageName())), REQUEST_APP_SETTING);
                    }
                }).show();
    }

    class AccessibilityServiceReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (!TextUtils.isEmpty(action)) {
                if (ACTION_ACCESSIBILITYSERVICE.equals(action)) {
                    sPayWebView.loadUrl(sPayInfo.getUrl());
                    sPayInfo.setIsPaying(true);
                }
            }
        }
    }

    private void registerAccessibilityServiceReceiver() {
        IntentFilter intentFilter = new IntentFilter(ACTION_ACCESSIBILITYSERVICE);
        LocalBroadcastManager.getInstance(this).registerReceiver(mAccessibilityServiceReceiver, intentFilter);
    }

    private void unRegisterAccessibilityServiceReceiver() {
        if (null != mAccessibilityServiceReceiver) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mAccessibilityServiceReceiver);
        }
    }
}

